import { GlobalService } from 'services/Api'

export const dialogUploadMixin = {
  data () {
    return {
      OSSPolicy: {},
      imgUpload: {
        count: 0
      },
      uploadImg: false,
      clearAllImgByToogle: false
    }
  },
  methods: {
    // 清除所有图片
    clearAllImgs () {
      this.clearAllImgByToogle = !this.clearAllImgByToogle
    },
    // 验证成功后，上传接口前-上传图片
    async beforeSubmit () {
      if (this.imgUpload.count) {
        this.uploadImg = !this.uploadImg
        await this.checkIsUploadComplete()
      }
    },
    uploadFileChange (param) {
      if (typeof this.addEditForm[param.model] !== 'object') this.imgUpload.count++
      this.addEditForm[param.model] = param.file
    },
    uploadSuccess (param) {
      this.addEditForm[param.model] = param.data
      this.imgUpload.count--
    },
    uploadError (param) {
      console.log(param)
      this.imgUpload.count--
      this.$message.error('上传图片失败，请重试')
    },
    async checkIsUploadComplete () {
      const upload = this.imgUpload
      return new Promise(resolve => {
        const interval = setInterval(() => {
          if (upload.count === 0) {
            clearInterval(interval)
            resolve()
          }
        }, 100)
      })
    }
  },
  async created () {
    const [ err, rs ] = await GlobalService.getOssPolicy({ acc_id: this.acc_id })
    if (err) return this.$message.error('获取上传签名失败')
    this.OSSPolicy = rs
  }
}
